<?php

namespace Admin\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\Page; 

class VestController extends BaseController {
	function _initialize() {
		parent::_initialize ();
	}

	public function index(){
        $this->display();
    }


    public function presaleList()
    {
  
    $_listrows = I('request.verypageshowcount', '', 'trim');
        $keywords = I('request.keywords','','trim');
        if(!empty($keywords)){
            $_where['g.user_id|g.user_name']=array('like',"%{$keywords}%");
        }
        $type = I('request.blongtype',-1,'intval');
		if( $type != -1){
			$_where['a.isactive']=$type;
		} 
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');
        $str='';
        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
        if(!(empty($start_time) && empty($end_time))){ 
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }  
  
           $str =" and a.addtime between '".$start_time." 00:00:01' and '".$end_time." 23:59:59'"; 
        }  
        
        $str = ltrim(trim($str),'and');
        if(!empty($str)){
            $_where['_string']=$str;
        }
        $where_order['where'] = $_where;
        $where_order['order'] = ' last_transaction_time desc ';
        $where_order['listrows'] = $_listrows;
        $where_order["id"]="load_tb_div";
        $where_order["alias"]="a";
        $where_order["order"]="a.addtime desc";
        $where_order["field"]="a.*,g.user_name,g.nickname,g.is_vip,u.user_name as admin_username";
        $where_order["join"]=array('inner join '.$this->dbprefix.'users g on a.userid=g.user_id',' inner join '.$this->dbprefix.'admin_user u on a.adminuserid=u.user_id');   

        $_datalist = $this->_getListsFromModel('group_system_user', $where_order);
        $this->assign('_datalist', $_datalist);
        $this->display(); 
 

    }

public function add_group(){
	//$blongtype = I('request.blongtype', '', 'trim');
	$this->assign('blongtype','group');
   $this->display();

}





 public function  goods_list(){
 	    $_listrows = I('request._listrows', '', 'trim');
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
		   $_where['user_name|user_id']=array('like',"%{$keywords}%");
		} 
		
		$where_order['where'] = $_where;
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div"; 
	/*	$where_order["field"]="a.*,CASE WHEN c.measure_unit='' THEN '千克' ELSE measure_unit END AS measure_unit";*/
		$where_order['alias']="a";
		$where_order['order']="a.user_id asc";
		/*$where_order["join"] =array(' INNER JOIN `'.$this->dbprefix.'category` c ON a.cat_id=c.cat_id');*/
		
        $_datalist = $this->_getListsFromModel('users', $where_order);
        //查询改订单是否有赠品 
        $sqllist = D('group_system_user')->select();
         if(!empty($sqllist)){
            $this->assign('sqllist',json_encode($sqllist));
         }
      	$this->assign('_datalist', $_datalist);
		$this->display('goods_list');
 }	




 public function add_goods(){
        $ret=array('staute'=>'error','msg'=>"保存失败");
		$postdata=I("json");
		
		if(empty($postdata)){
			$ret=array('staute'=>'error','msg'=>"传输参数错误");
			$this->ajaxReturn ($ret);
			exit;
		} 
		
		$json = json_decode($postdata,true); 
		if(!is_array($json)){
			$ret=array('staute'=>'error','msg'=>"商品信息错误");
			$this->ajaxReturn ($ret);
			exit;
		}
		//对数据进行处理
		 $sl=M("group_system_user");
		 $dblist= $sl->where($where)->select(); //数据库当前主题存在的记录信息;
		 
		 $aryadd=$arydel=$aryupd=array();
		 //提交数据 是否在数据库中存在，存在更新否则增加
		 foreach($json as $k=>$v){ 
		 	$flg=0;
		 	foreach ($dblist as $key=>$o){ 
		 	  if( $v["sysid"]==$o["sysid"] && $v["userid"]==$o['userid']){
		 	  	  $aryupd[]=$v;		
		 	  	  $flg=1;
		 	  	  break;
		 	  }
		 	}
		   if($flg==0){
		     	$aryadd[]=$v;
		   }
		 }
		 
		 //在数据库里存在，但是提交的数据不存在，删除数据
		 foreach ($dblist as $key=>$o){
		 	$bl=0;
		 	foreach($json as $k=>$v){
		 	  if($v["sysid"]==$o["sysid"] && $v["userid"]==$o['userid']){ 
		 			$bl=1;
		 			break;
		 		}
		 	}
		 	if($bl==0){
		 		$arydel[]=$o;
		 	}
		 }
		  
		 $sqladd=$sqlupd=$sqldel="";
		 $arysqlupd=array();  
		 $time=date("Y-m-d H:i:s");
		 


		 //构建插入数据语句
		 if(count($aryadd)>0){
		 	$sqlval=""; 
		 	foreach ($aryadd as $k=>$v){
		 		$listid=getGuid();//创建guid值
		 		$sqlval.=((empty($sqlval)?"":",")."('$listid','".$v['userid']."','1','".$time."',".UID.",'0')");
		 	}
		 	$sqladd=" INSERT INTO  ".$this->dbprefix."group_system_user(`sysid`,`userid`,`isactive`,`addtime`,`adminuserid`,`num`) values ".$sqlval;
		 }
		 
		 //构建更新数据语句
/*		 if(count($aryupd)>0){  
		 	foreach ($aryupd as $k=>$v){
		 		$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
		 		$sqlupd="update ".$this->dbprefix."wx_parcellist set parcelid='$parcel',pb_id='".$v['pb_id']."',goodsid='".$v['goodsid']."',goodsname='".$v['goodsname']."',price='".$v['price']."',unit='".$v['unit']."',logistics_price='".$v['logistics_price']."',weight='".$v['weight']."',money='".$money."',operationuser='".UID."',createtime='".$time."' where listid='".$v['listid']."'";
		 		$arysqlupd[]=$sqlupd;
		 	} 
		 }*/
		
		 //构建删除数据语句
		 if(count($arydel)>0){
		 	$sqlval="";
		 	foreach ($arydel as $k=>$v){
		 		$sqlval.=((empty($sqlval)?"":",").$v['sysid']);
		 	}
		 	if(!empty($sqlval))
		 	   $sqldel="delete from ".$this->dbprefix."group_system_user where FIND_IN_SET(`sysid`,'".$sqlval."')";
		 }
		 
		 $db=M("group_system_user");
		 $retadd=$retupd= $retdel=1; //默认是成功状态
		 
		 $db->startTrans(); //启动事务
		 
		 if($sqladd){
		    $retadd=$db->execute($sqladd);
		 } 
		 
		 if($sqldel){
		    $retdel=$db->execute($sqldel);
		 }
		 
		 if($retadd  && $retdel){
		    $db->commit();
		    $ret=array('staute'=>'success','msg'=>"保存数据成功");
		 }
		 else {
		    $db->rollback();
		    $ret=array('staute'=>'error','msg'=>"保存数据失败");
		 }  
		$this->ajaxReturn($ret);

 }

//这是有效无效
public function set_user_state(){
	$ret=array('staute'=>'error','msg'=>"保存失败");
	$id=I("id");
	$save['isactive'] = I("isactive");

       $res  =  D("group_system_user")->where("sysid='".$id."'")->find();
       if(!$res){
         $this->error("删除失败");
       }
       $where['a.userid'] = $res['userid'];
       $time = date('Y-m-d H:i:s');
       $where['b.endtime'] = array('gt',$time);
       $sql = D('group_list')->alias('a')->join('inner join ki_group_purchase_package as b on a.packageid = b.packageid')->where($where)->find();
		if(empty($id)||!isset($save['isactive'])){
			$ret=array('staute'=>'error','msg'=>"传输参数错误");
			$this->ajaxReturn ($ret);
			exit;
		}
       if(empty($sql) || !isset($sql)){
				$res = D('group_system_user')->where("sysid='".$id."'")->save($save);
				if($res){
					$ret=array('staute'=>'success','msg'=>"保存数据成功");
				}else{
					$ret=array('staute'=>'error','msg'=>"保存数据失败");
				}
		 }else{
		 	$ret=array('staute'=>'success','msg'=>"该会员已经在包里面，不能操作！");
		  }

		$this->ajaxReturn($ret);
}


//批量有效无效设置
  public function batch_set_user(){
	$ret=array('staute'=>'error','msg'=>"保存失败");
	$id=I("id");
	$save['isactive'] = I("isactive");
	if(empty($id)||!isset($save['isactive'])){
		$ret=array('staute'=>'error','msg'=>"传输参数错误");
		$this->ajaxReturn ($ret);
		exit;
	}
       $arrid = explode(',',$id);
        $tmp = array();
        $res = array();
        foreach ($arrid as $key => $value) {
       $res  =  D("group_system_user")->where("sysid = ".$value)->find();
         $where['a.userid'] = $res['userid'];

	   $time = date('Y-m-d H:i:s');
       $where['b.endtime'] = array('gt',$time);
       $sql = D('group_list')->alias('a')->join('inner join ki_group_purchase_package as b on a.packageid = b.packageid')->where($where)->find();
	     if(empty($sql) || !isset($sql)){
	     	array_push($tmp,$value);
	     }
      }
    $_arr_id = implode(',',$tmp );
    
    if($_arr_id == ""){
       $ret=array('staute'=>'success','msg'=>"所有的会员都在包中，不能操作！");
       $this->ajaxReturn($ret);
    }

  	$res = D('group_system_user')->where("sysid in(".$_arr_id.")")->save($save);
	if(!$res){
		$ret=array('staute'=>'error','msg'=>"批量保存数据失败");	
		$this->ajaxReturn($ret);	
	}
	$ret=array('staute'=>'success','msg'=>"批量操作成功");
	if(count($tmp) < count($arrid)){
        $ret=array('staute'=>'success','msg'=>"批量操作成功!,有些包中的商品不能操作！");
	}
   $this->ajaxReturn($ret);	

}

 public function delete_wx_presale(){
     if(IS_GET){
        $map['sysid'] = I('get.id');
       $res  =  D("group_system_user")->where($map)->find();
       if(!$res){
         $this->error("删除失败");
       }
       $where['a.userid'] = $res['userid'];
       $time = date('Y-m-d H:i:s');
       $where['b.endtime'] = array('gt',$time);
       $sql = D('group_list')->alias('a')->join('inner join ki_group_purchase_package as b on a.packageid = b.packageid')->where($where)->find();
       if(empty($sql) || !isset($sql)){
	        $row = D('group_system_user')->where($map)->delete();
	        if($row != flase){
	        	$this->success("删除成功") ;
	        }else{
	        	$this->error("删除失败") ;
	        }
	 }else{
         $this->success("该会员已近在包里面，不能删除！") ;
	  }


     }
 }


 public function all_delete_wx_vest(){
     if(IS_POST){
        $allid = I('post.allid');
        $arrid = explode(',',$allid);
        $tmp = array();
        $res = array();
	        foreach ($arrid as $key => $value) {
	          $res  =  D("group_system_user")->where("sysid = ".$value)->find();
	             $where['a.userid'] = $res['userid'];
			            $time = date('Y-m-d H:i:s');
       					$where['b.endtime'] = array('gt',$time);
       					$sql = D('group_list')->alias('a')->join('inner join ki_group_purchase_package as b on a.packageid = b.packageid')->where($where)->find();
			     if(empty($sql) || !isset($sql)){
			     	array_push($tmp,$value);
			     }
	        }
        $_arr_id = implode(',',$tmp );
        if($_arr_id != ""){
               $where = "sysid in (".$_arr_id.")";
		        $row = D('group_system_user')->where($where)->delete();
		        if($row != flase){
			        if(count($tmp) < count($arrid)){
	                        $ret=array('staute'=>'success','msg'=>"批量操作成功!,有些包中的商品不能操作！");
		           	}else{
		           		
			        	   $ret=array('staute'=>'success','msg'=>"批量操作成功");
			        	}
		        }else{
		        	 $ret=array('staute'=>'error','msg'=>"批量操作失败");
		        }
		

		 }else{
	     $ret=array('staute'=>'success','msg'=>"所有的会员都在包中，不能操作！");
		 }
	   $this->ajaxReturn($ret);
	 }
 }


 
}
?>
